package com.club.football.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.club.football.common.UserHolder;
import com.club.football.dto.ClubSaveDto;
import com.club.football.dto.PageDto;
import com.club.football.entity.Club;
import com.club.football.mapper.ClubMapper;
import com.club.football.req.ClubPageReq;
import com.club.football.service.ClubService;
import com.club.football.utils.BeanUtils;
import com.club.football.utils.FileUtils;
import com.club.football.utils.R;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.club.football.common.CommonConstants.*;

/**
 * 俱乐部服务实现
 *
 * @author 1
 * @date 2023/12/28
 */
@Service
public class ClubServiceImpl extends ServiceImpl<ClubMapper, Club> implements ClubService {
    @Override
    public R<PageDto<Club>> clubPage(PageDto<Club> pageDto, ClubPageReq clubPageReq) {
        lambdaQuery().like(StringUtils.isNotBlank(clubPageReq.getClubName()), Club::getClubName, clubPageReq.getClubName())
                .page(pageDto);
        List<Club> records = pageDto.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            records.forEach(e -> {
                String clubLogo = e.getClubLogo();
                if (StringUtils.isNotBlank(clubLogo)) {
                    e.setClubLogo(FileUtils.getUrl(e.getClubLogo()));
                }
            });
            pageDto.setRecords(records);
        }
        return R.ok(pageDto, GET_INFO_OK);
    }

    @Override
    public R<String> clubSave(ClubSaveDto saveDto) {
        Club club = BeanUtils.copier(saveDto, new Club());
        Long userId = UserHolder.getUser().getUserId();
        club.setUpdateBy(userId);
        String clubLogo = club.getClubLogo();
        if (null != saveDto.getClubId()) {
            if (StringUtils.isBlank(clubLogo)) {
                club.setClubLogo(getById(saveDto.getClubId()).getClubLogo());
            }
            updateById(club);
            return R.ok(EDIT_OK_MSG);
        }
        club.setCreateBy(userId);

        if (StringUtils.isBlank(clubLogo)) {
            club.setClubLogo(FileUtils.getImageUrl(DEFAULT_IMAGE));
        }
        save(club);
        return R.ok(SAVE_OK_MSG);
    }
}
